<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="loadListData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表
      listLoading：加载效果

    -->
    <el-table :data="listData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" :formatter="formatSex" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" >
      </el-table-column>
      <el-table-column prop="employee.username" label="负责人" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total, sizes,prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :page-sizes="[5, 10, 20, 50]"
                     :page-size="pageSize"
                     :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增界面
      :rules:添加校验规则
        prop="sn"：具体要使用的规则
    -->
    <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="editForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="0">启用</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理" >
          <el-select  v-model="addForm.employee" placeholder="请选择" value-key="id">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" >
          <el-cascader v-model="addForm.parent"
                       :options="deptTrees"
                       :props="{
                checkStrictly: true,
                label:'name',
                value:'id'
               }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>


<script>
import {addUser, batchRemoveUser} from "../../api/api";
import util from "../../common/js/util";

export default {
  data() {
    return{
      listData:[],
      listLoading:true,
      sels:[],
      total:0,
      pageSize:10,
      page:1,//展示的第几页
      filters: {
        name: ''
      },
      addFormVisible:false,
      addLoading:false,

      addForm:{
        sn: '',
        name: '',
        state: 0,
        manager_id: null,
        parent_id: null,
        employee:{

        },
        parent:{
          id:null
        }
      },
      parent:{

      },
      addFormRules:{
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入部门编号 ', trigger: 'blur' }
        ]
      },
      title:"",
      employees:[],
      deptTrees:[]
    }
  },

  methods:{
    addSubmit(){
      this.$refs.editForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let arr = this.addForm.parent;
            if (Array.isArray(arr)){
              this.addForm.parent = {
                id:arr[arr.length-1]
              }
            }else {
              if (this.title === "编辑"){
                this.addForm.parent = {
                  id:arr
                }
              }
            }
            let param = Object.assign({},this.addForm)
            this.$http.put("/department",param).then(res=>{
              //关闭按钮加载
              this.addLoading = false;

              let {success,message} = res.data;
              if (success){
                this.$message({
                  message:"操作成功！！！",
                  type:"success"
                });
              }else {
                this.$message.error("网络繁忙，请重试！！！")
              }
            })
            //关闭模态框
            this.addFormVisible = false;
            this.loadListData();
          });
        }
      });
    },
    //打开新增模态框
    handleAdd(){
      this.addForm = {
        sn: '',
        name: '',
        state: 0,
        manager_id: null,
        parent_id: null,
      }
      this.addFormVisible = true;
      this.title=("新增");
    },
    handleSizeChange(val){
      this.pageSize=val;
      this.loadListData();
    },
    handleCurrentChange(val){
      this.page=val;
      this.loadListData();
    },
    //发送请求
    loadListData(){
      let param = {
        currentPage:this.page,
        pageSize:this.pageSize,
        keywords:this.filters.name,
      }
      this.$http.post("/department",param).then(res=>{
        console.log(res)
        this.listData=res.data.data;
        this.total=res.data.totals;
        this.listLoading=false;
      }).then(res=>{

      })
    },
    selsChange(sels) {
      this.sels = sels;
    },
    //性别显示转换
    formatSex(row, column) {
      return row.state == 0 ? '启用' : row.state == -1 ? '未启用' : '未知';
    },
    //显示编辑界面
    handleEdit(index, row) {
      //回显数据
      this.addForm = Object.assign({},row);
      this.addForm.parent=row.parent.id
      //打开模态框
      this.addFormVisible = true;
      this.title = "修改"
    },

    //批量删除
    batchRemove() {
      var ids = this.sels.map(item => item.id);
      console.log(ids)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/department",ids).then(row=>{
          let {success,message} = row.data;
          if (success){
            this.$message({
              message:"删除成功！！！",
              type:"success"
            });
          }else {
            this.$message.error("网络繁忙，请重试！！！")
          }
        })
        //刷新列表
        this.loadListData();
      }).catch(() => {
      });
    },

    //单个删除
    handleDel: function (index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/"+row.id).then(row=>{
          let {success,message} = row.data;
          if (success){
            this.$message({
              message:"删除成功！！！",
              type:"success"
            });
          }else {
            this.$message.error("网络繁忙，请重试！！！")
          }
          //刷新列表
          this.loadListData();
        })

      }).catch(() => {
        this.$message('取消删除！！！');
      });
    },
    loadEmps(){
      this.$http.get("employee").then(res=>{
        this.employees = res.data;
      })
    },
    loadTrees(){
      this.$http.get("/department/deptTree").then(res=>{
        this.deptTrees = res.data;
      })
    }
  },
  mounted() {
    this.loadListData();
    this.loadEmps();
    this.loadTrees();
  }
}


</script>

<style scoped>

</style>